package com.fingard.dsp.bank.directbank.cqsx01;

import com.fingard.text.StringHelper;
import org.apache.commons.lang.StringUtils;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.xml.XmlTextWriter;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

/**
 * Created by dalt on 2017/6/20.
 */
public abstract class CQSX01Base extends DirectBase {
    protected final boolean DEBUG = true;
    protected final String successRetCode = "000000";

    protected String tranlateRetCode(String retCode) {
        return StringUtils.equals(successRetCode, retCode) ? "0" : "-1";
    }

    protected String convertCurToBank(String cur) throws Exception {
        return getBankConfig().getMapValueByKey("currencyMapping", cur);
    }

    protected String convertCurToATS(String cur) throws Exception {
        return getBankConfig().getMapKeyByValue("currencyMapping", cur);
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, CQSX01Header p_bankHeader) throws Exception {
    }

    protected boolean isActiveRetCode(String code)
    {
        return successRetCode.equals(code);
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String[] sendToBank(String p_reqStr,String transType,String commandCode,String transcode) throws Exception {
        String[] retStr = new String[]{"", ""};
        //后置挡板
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, p_reqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        return sendToBank(p_reqStr,transcode);
    }

    protected String[] sendToBank(String p_reqStr, String transcode) throws UnsupportedEncodingException {
        String[] retStr = new String[]{"", ""};
        String targetUrl = bankFront.serverURL.replaceAll("TransCode", transcode);
        WriteBankLogLn("2.提交银行的地址：" + targetUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(targetUrl);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = getCharset();
        byte[] tmpUpBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpUpBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        if (retStr[0].length() == 0) {
            int tmpIndex = retStr[1].indexOf("<");
            if (tmpIndex > 0) {
                retStr[1] = retStr[1].substring(tmpIndex);
            }
        }
        return retStr;
    }

    protected String parseSeq(String seq) {
        return new BigInteger(seq, 36).toString(10);
    }
}
